package service.array;

import domain.dto.BaseDto;

import domain.entity.BaseEntity;

import domain.vo.BaseVo;

import domain.vo.Result;
import service.IBaseService;

import java.util.Arrays;

abstract class Baseservice <
        Entity extends BaseEntity,
        Dto extends BaseDto,
        Vo  extends BaseVo>
        implements IBaseService<Entity,Dto> {

     static  final int DATA_SIZE=100;

    Entity[] date;

    Vo[] temp;


    private  int idCounter = 1;

    @Override
    public boolean existById(int id) {
        return id>=1 && id<idCounter && date[id]!=null;

    }

    @Override
    public Entity findById(int id) {
        if(existById(id)){
            return date[id];
        }
        return null;
    }

    abstract Vo convertToVo(Entity entity);
    @Override
    public Result list() {

        int length=0;
        for(int i=1;i<idCounter;i++){
            if(date[i]!=null){
                temp[length++]=convertToVo(date[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp,length));

    }

    abstract Entity createEntity(Dto dto, int id);


        @Override
    public Result create(Dto dto) {
        if(idCounter>DATA_SIZE){
            return Result.failure("创建失败，超出了存储容量");
        }
       Entity entity=createEntity(dto,idCounter++);
        date[entity.getId()]=entity;
        return Result.success("创建成功",null);

    }

    abstract void updateEntity(Dto dto, Entity entity);

    @Override
    public Result update(Dto dto, int id) {
        if(!existById(id)){
            return Result.failure("更新失败，不存在该数据");
        }
        Entity entity=date[id];
        updateEntity(dto,entity);
        return Result.success("更新成功",null);
    }
}
